<?php
require_once __DIR__ . '/../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问此页面', 'danger');
}

// 获取筛选条件
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;

// 构建查询条件
$where = ['1=1'];
$params = [];

if ($search) {
    $where[] = '(username LIKE ? OR phone LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status !== '') {
    $where[] = 'status = ?';
    $params[] = intval($status);
}

$whereClause = implode(' AND ', $where);

// 获取用户总数
$db = getDB();
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE $whereClause");
$stmt->execute($params);
$total = $stmt->fetchColumn();

// 计算分页
$totalPages = ceil($total / $perPage);
$page = min($page, $totalPages ?: 1);
$offset = ($page - 1) * $perPage;

// 获取用户列表
$stmt = $db->prepare("SELECT * FROM users WHERE $whereClause ORDER BY created_at DESC LIMIT $offset, $perPage");
$stmt->execute($params);
$users = $stmt->fetchAll();

// 处理用户状态变更
// 处理用户状态变更
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $userId = intval($_POST['user_id'] ?? 0);
    
    if ($userId <= 0) {
        $error = '用户ID无效';
    } elseif ($userId == $_SESSION['user_id']) {
        $error = '不能操作自己的账号';
    } else {
        if ($action == 'toggle_status') {
            $stmt = $db->prepare("UPDATE users SET status = CASE WHEN status = 1 THEN 0 ELSE 1 END WHERE id = ?");
            if ($stmt->execute([$userId])) {
                $success = '用户状态更新成功';
            } else {
                $error = '操作失败';
            }
        } elseif ($action == 'delete') {
            $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
            if ($stmt->execute([$userId])) {
                $success = '用户删除成功';
            } else {
                $error = '删除失败';
            }
        } elseif ($action == 'approve_user') {
            $stmt = $db->prepare("UPDATE users SET is_approved = 1, approved_at = NOW(), approved_by = ? WHERE id = ?");
            if ($stmt->execute([$_SESSION['user_id'], $userId])) {
                $success = '用户审批成功';
            } else {
                $error = '审批失败';
            }
        } 
        // 添加重置密码处理
        elseif ($action == 'reset_password') {
            $newPassword = '12345678';
            $hashedPassword = passwordHash($newPassword);
            $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
            if ($stmt->execute([$hashedPassword, $userId])) {
                $success = '用户密码已重置为 12345678';
            } else {
                $error = '密码重置失败';
            }
        }
    }
    
    // 重新获取用户列表
    $stmt = $db->prepare("SELECT * FROM users WHERE $whereClause ORDER BY created_at DESC LIMIT $offset, $perPage");
    $stmt->execute($params);
    $users = $stmt->fetchAll();
}

include __DIR__ . '/header.php';
?>


            
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">用户管理</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                            <i class="bi bi-person-plus"></i> 添加用户
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-success" id="batchApproveBtn" onclick="batchApprove()" disabled>
                            <i class="bi bi-check-circle"></i> 批量审批 (<span id="selectedCount">0</span>)
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-info" onclick="approveAll()">
                            <i class="bi bi-check-all"></i> 一键审批所有未审批用户
                        </button>
                    </div>
                </div>
            </div>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if (isset($success)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- 筛选器 -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-4">
                            <label for="search" class="form-label">搜索用户</label>
                            <input type="text" class="form-control" id="search" name="search" 
                                   placeholder="用户名或手机号" value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="status" class="form-label">状态</label>
                            <select class="form-select" id="status" name="status">
                                <option value="">全部状态</option>
                                <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>正常</option>
                                <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>禁用</option>
                            </select>
                        </div>
                        <div class="col-md-5 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <a href="users.php" class="btn btn-secondary">
                                <i class="bi bi-arrow-counterclockwise"></i> 重置
                            </a>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- 在筛选器后面添加批量操作提示 -->
            <div id="batchActions" class="alert alert-info d-none mb-4">
                <div class="d-flex justify-content-between align-items-center">
                    <span>已选择 <strong id="selectedUsersCount">0</strong> 个用户</span>
                    <div>
                        <button type="button" class="btn btn-sm btn-success me-2" onclick="batchApprove()">
                            <i class="bi bi-check-circle"></i> 审批选中用户
                        </button>
                        <button type="button" class="btn btn-sm btn-secondary" onclick="clearSelection()">
                            <i class="bi bi-x-circle"></i> 清除选择
                        </button>
                    </div>
                </div>
            </div>

            <!-- 用户列表 -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th width="50">
                                        <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)">
                                    </th>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>手机号</th>
                                    <th>状态</th>
                                    <th>类型</th>
                                    <th>审批状态</th>
                                    <th>注册时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            
                            <!-- 修改表格内容 -->
                            <tbody>
                                <?php if (empty($users)): ?>
                                    <tr>
                                        <td colspan="9" class="text-center text-muted py-4">
                                            <i class="bi bi-inbox display-4"></i>
                                            <p class="mt-2 mb-0">暂无用户数据</p>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($users as $user): ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" class="user-checkbox" value="<?php echo $user['id']; ?>" 
                                                       onchange="updateBatchActions()">
                                            </td>
                                            <td><?php echo $user['id']; ?></td>
                                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                                            <td><?php echo htmlspecialchars($user['phone']); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $user['status'] ? 'success' : 'danger'; ?>">
                                                    <?php echo $user['status'] ? '正常' : '禁用'; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $user['is_admin'] ? 'warning' : 'info'; ?>">
                                                    <?php echo $user['is_admin'] ? '管理员' : '普通用户'; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $user['is_approved'] ? 'success' : 'warning'; ?>">
                                                    <?php echo $user['is_approved'] ? '已审批' : '待审批'; ?>
                                                </span>
                                            </td>
               
                                                <td><?php echo formatTime($user['created_at']); ?></td>
                                                <td>
                                                    <div class="btn-group" role="group">
                                                        <!-- 查看详情按钮 -->
                                                        <button type="button" class="btn btn-sm btn-outline-primary" 
                                                                onclick="viewUser(<?php echo $user['id']; ?>)"
                                                                data-bs-toggle="tooltip" title="查看详情">
                                                            <i class="bi bi-eye"></i>
                                                        </button>
                                                        
                                                        <!-- 审批按钮（如果未审批） -->
                                                        <?php if (!$user['is_approved']): ?>
                                                            <form method="POST" style="display: inline;">
                                                                <input type="hidden" name="action" value="approve_user">
                                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                                <button type="submit" class="btn btn-sm btn-outline-success" 
                                                                        data-bs-toggle="tooltip" title="审批通过">
                                                                    <i class="bi bi-check-circle"></i>
                                                                </button>
                                                            </form>
                                                        <?php endif; ?>
                                                        
                                                        <!-- 编辑按钮 -->
                                                        <button type="button" class="btn btn-sm btn-outline-info" 
                                                                onclick="editUser(<?php echo $user['id']; ?>)"
                                                                data-bs-toggle="tooltip" title="编辑用户">
                                                            <i class="bi bi-pencil"></i>
                                                        </button>
                                                        
                                                        <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                                        
                                                       
                                                            <!-- 重置密码按钮 -->
                                                            <form method="POST" style="display: inline;" 
                                                                  onsubmit="return confirm('确定要将用户 <?php echo htmlspecialchars($user['username']); ?> 的密码重置为 12345678 吗？');">
                                                                <input type="hidden" name="action" value="reset_password">
                                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                                <button type="submit" class="btn btn-sm btn-outline-secondary" 
                                                                        data-bs-toggle="tooltip" title="重置密码">
                                                                    <i class="bi bi-key"></i>
                                                                </button>
                                                            </form>
                                                            <!-- 状态切换按钮 -->
                                                            <form method="POST" style="display: inline;">
                                                                <input type="hidden" name="action" value="toggle_status">
                                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                                <button type="submit" class="btn btn-sm btn-outline-warning" 
                                                                        data-bs-toggle="tooltip" title="<?php echo $user['status'] ? '禁用' : '启用'; ?>">
                                                                    <i class="bi bi-<?php echo $user['status'] ? 'toggle-on' : 'toggle-off'; ?>"></i>
                                                                </button>
                                                            </form>
                                                            
                                                            <!-- 删除按钮 -->
                                                            <form method="POST" style="display: inline;" 
                                                                  onsubmit="return confirm('确定要删除这个用户吗？此操作不可恢复！');">
                                                                <input type="hidden" name="action" value="delete">
                                                                <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                                <button type="submit" class="btn btn-sm btn-outline-danger" 
                                                                        data-bs-toggle="tooltip" title="删除">
                                                                    <i class="bi bi-trash"></i>
                                                                </button>
                                                            </form>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页 -->
                    <?php if ($totalPages > 1): ?>
                        <nav aria-label="用户分页" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>">
                                        <i class="bi bi-chevron-left"></i> 上一页
                                    </a>
                                </li>
                                
                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                    <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>">
                                                <?php echo $i; ?>
                                            </a>
                                        </li>
                                    <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">...</span>
                                        </li>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>">
                                        下一页 <i class="bi bi-chevron-right"></i>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>


<!-- 添加用户模态框 -->
<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm" class="needs-validation" novalidate>
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="username" name="username" required>
                        <div class="invalid-feedback">请输入用户名</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="phone" class="form-label">手机号 <span class="text-danger">*</span></label>
                        <input type="tel" class="form-control" id="phone" name="phone" required pattern="^1[3-9]\d{9}$">
                        <div class="invalid-feedback">请输入正确的手机号</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password" class="form-label">密码 <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="password" name="password" required minlength="6">
                        <div class="invalid-feedback">密码长度不能少于6位</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="is_admin" class="form-label">用户类型</label>
                        <select class="form-select" id="is_admin" name="is_admin">
                            <option value="0">普通用户</option>
                            <option value="1">管理员</option>
                        </select>
                    </div>
                    
                    <div class="text-end">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary" id="addUserSubmit">
                            <i class="bi bi-person-plus"></i> 添加用户
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- 在 users.php 的模态框部分添加编辑模态框 -->
<!-- 编辑用户模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑用户信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- 内容将通过JavaScript动态加载 -->
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">加载中...</p>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 用户详情模态框 -->
<div class="modal fade" id="userDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">用户详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="userDetailsContent">
                <!-- 详情内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<script>
function viewUser(userId) {
    // 显示加载状态
    document.getElementById('userDetailsContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('userDetailsModal'));
    modal.show();
    
    // 加载用户详情
    fetch('api/user_details.php?id=' + userId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const user = data.data;
                const statusClass = user.status ? 'success' : 'danger';
                const statusText = user.status ? '正常' : '禁用';
                const typeClass = user.is_admin ? 'warning' : 'info';
                const typeText = user.is_admin ? '管理员' : '普通用户';
                const approvalClass = user.is_approved ? 'success' : 'warning';
                const approvalText = user.is_approved ? '已审批' : '待审批';
                
                let html = `
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>用户ID：</strong></td><td>${user.id}</td></tr>
                                <tr><td><strong>用户名：</strong></td><td>${user.username}</td></tr>
                                <tr><td><strong>手机号：</strong></td><td>${user.phone}</td></tr>
                                <tr><td><strong>状态：</strong></td><td>
                                    <span class="badge bg-${statusClass}">${statusText}</span>
                                </td></tr>
                                <tr><td><strong>类型：</strong></td><td>
                                    <span class="badge bg-${typeClass}">${typeText}</span>
                                </td></tr>
                                <tr><td><strong>审批状态：</strong></td><td>
                                    <span class="badge bg-${approvalClass}">${approvalText}</span>
                                </td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>注册时间：</strong></td><td>${new Date(user.created_at).toLocaleString('zh-CN')}</td></tr>
                                <tr><td><strong>最后更新：</strong></td><td>${new Date(user.updated_at).toLocaleString('zh-CN')}</td></tr>
                `;
                
                // 添加审批信息（如果已审批）
                if (user.is_approved) {
                    html += `
                                <tr><td><strong>审批时间：</strong></td><td>${user.approved_at ? new Date(user.approved_at).toLocaleString('zh-CN') : '未知'}</td></tr>
                                <tr><td><strong>审批人：</strong></td><td>${user.approver_name || '未知'}</td></tr>
                    `;
                }
                
                html += `
                                <tr><td><strong>PushPlus密钥：</strong></td><td>
                                    ${user.pushplus_token ? '已设置' : '未设置'}
                                </td></tr>
                                <tr><td><strong>推送状态：</strong></td><td>
                                    ${user.pushplus_enabled ? '已开启' : '已关闭'}
                                </td></tr>
                            </table>
                        </div>
                    </div>
                `;
                
                // 收款码
                html += `
                    <div class="row mt-4">
                        <div class="col-md-6">
                            <h6>微信收款码</h6>
                `;
                
                if (user.wechat_qr) {
                    html += `<img src="${user.wechat_qr_url}" class="img-fluid rounded border" style="max-height: 200px;">`;
                } else {
                    html += `<div class="text-muted">暂未上传</div>`;
                }
                
                html += `
                        </div>
                        <div class="col-md-6">
                            <h6>支付宝收款码</h6>
                `;
                
                if (user.alipay_qr) {
                    html += `<img src="${user.alipay_qr_url}" class="img-fluid rounded border" style="max-height: 200px;">`;
                } else {
                    html += `<div class="text-muted">暂未上传</div>`;
                }
                
                html += `
                        </div>
                    </div>
                `;
                
                // 统计信息
                html += `
                    <div class="row mt-4">
                        <div class="col-12">
                            <h6>订单统计</h6>
                            <div class="row">
                                <div class="col-md-3 text-center">
                                    <h4 class="text-warning">${user.order_stats.pending || 0}</h4>
                                    <p class="text-muted">未结算</p>
                                </div>
                                <div class="col-md-3 text-center">
                                    <h4 class="text-success">${user.order_stats.settled || 0}</h4>
                                    <p class="text-muted">已结算</p>
                                </div>
                                <div class="col-md-3 text-center">
                                    <h4 class="text-danger">${user.order_stats.refunded || 0}</h4>
                                    <p class="text-muted">已退还</p>
                                </div>
                                <div class="col-md-3 text-center">
                                    <h4 class="text-primary">${user.order_stats.total || 0}</h4>
                                    <p class="text-muted">总订单</p>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('userDetailsContent').innerHTML = html;
            } else {
                document.getElementById('userDetailsContent').innerHTML = `
                    <div class="alert alert-danger">${data.message || '加载失败'}</div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('userDetailsContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

// 表单验证
document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('.needs-validation');
    Array.prototype.filter.call(forms, function(form) {
        form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });
});

// 编辑用户
function editUser(userId) {
    // 显示加载状态
    const modalContent = document.getElementById('userDetailsContent');
    modalContent.innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示编辑模态框
    const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
    modal.show();
    
    // 加载用户信息
    fetch('api/get_user.php?id=' + userId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const user = data.data;
                
                // 构建编辑表单HTML，直接在模板中设置值
                const formHTML = `
                    <form id="editUserForm" class="needs-validation" novalidate>
                        <input type="hidden" id="edit_user_id" name="user_id" value="${user.id}">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_username" class="form-label">用户名</label>
                                    <input type="text" class="form-control" id="edit_username" name="username" 
                                           value="${user.username || ''}" required>
                                    <div class="invalid-feedback">请输入用户名</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_phone" class="form-label">手机号</label>
                                    <input type="tel" class="form-control" id="edit_phone" name="phone" 
                                           value="${user.phone || ''}" required pattern="^1[3-9]\\d{9}$">
                                    <div class="invalid-feedback">请输入正确的手机号</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_group_name" class="form-label">所在群组</label>
                                    <input type="text" class="form-control" id="edit_group_name" name="group_name" 
                                           value="${user.group_name || ''}">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_wechat_nickname" class="form-label">微信昵称</label>
                                    <input type="text" class="form-control" id="edit_wechat_nickname" name="wechat_nickname" 
                                           value="${user.wechat_nickname || ''}">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_wechat_account" class="form-label">微信号</label>
                                    <input type="text" class="form-control" id="edit_wechat_account" name="wechat_account" 
                                           value="${user.wechat_account || ''}">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_alipay_account" class="form-label">支付宝账号</label>
                                    <input type="text" class="form-control" id="edit_alipay_account" name="alipay_account" 
                                           value="${user.alipay_account || ''}">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_account_holder" class="form-label">开户人姓名</label>
                                    <input type="text" class="form-control" id="edit_account_holder" name="account_holder" 
                                           value="${user.account_holder || ''}">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_bank_name" class="form-label">银行名称</label>
                                    <input type="text" class="form-control" id="edit_bank_name" name="bank_name" 
                                           value="${user.bank_name || ''}">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_bank_card_number" class="form-label">银行卡号</label>
                            <input type="text" class="form-control" id="edit_bank_card_number" name="bank_card_number" 
                                   value="${user.bank_card_number || ''}" pattern="\\d{16,23}" 
                                   oninput="formatBankCard(this)" maxlength="23">
                            <div class="invalid-feedback">请输入正确的银行卡号（16-19位数字）</div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="edit_status" name="status" value="1" 
                                       ${user.status == 1 ? 'checked' : ''}>
                                <label class="form-check-label" for="edit_status">用户状态（启用）</label>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="edit_is_admin" name="is_admin" value="1" 
                                       ${user.is_admin == 1 ? 'checked' : ''}>
                                <label class="form-check-label" for="edit_is_admin">管理员权限</label>
                            </div>
                        </div>
                        
                        <div class="text-end">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="submit" class="btn btn-primary" id="editUserSubmit">
                                <i class="bi bi-save"></i> 保存修改
                            </button>
                        </div>
                    </form>
                `;
                
                // 设置模态框内容
                const editModalBody = document.querySelector('#editUserModal .modal-body');
                editModalBody.innerHTML = formHTML;
                
                // 格式化银行卡号显示
                const bankCardInput = document.getElementById('edit_bank_card_number');
                if (bankCardInput && bankCardInput.value) {
                    formatBankCard(bankCardInput);
                }
                
                // 绑定表单提交事件
                document.getElementById('editUserForm').addEventListener('submit', handleEditUserSubmit);
                
            } else {
                const editModalBody = document.querySelector('#editUserModal .modal-body');
                editModalBody.innerHTML = `<div class="alert alert-danger">${data.message || '加载失败'}</div>`;
            }
        })
        .catch(error => {
            const editModalBody = document.querySelector('#editUserModal .modal-body');
            editModalBody.innerHTML = `<div class="alert alert-danger">加载失败：${error.message}</div>`;
        });
}

// 银行卡号格式化函数（实时格式化显示，但存储纯数字）
function formatBankCard(input) {
    if (!input) return;
    
    // 获取光标位置
    let cursorPos = input.selectionStart;
    let originalValue = input.value;
    
    // 移除所有非数字字符
    let value = originalValue.replace(/\D/g, '');
    
    // 如果值为空，直接返回
    if (!value) return;
    
    // 格式化显示：每4位加一个空格
    let formattedValue = '';
    for (let i = 0; i < value.length; i++) {
        if (i > 0 && i % 4 === 0) {
            formattedValue += ' ';
        }
        formattedValue += value[i];
    }
    
    // 更新输入框值
    input.value = formattedValue;
    
    // 调整光标位置（考虑新增的空格）
    if (cursorPos > 0) {
        let addedSpaces = Math.floor((cursorPos - 1) / 4);
        let newCursorPos = cursorPos + addedSpaces;
        input.setSelectionRange(newCursorPos, newCursorPos);
    }
}

// 在表单提交前，移除银行卡号中的空格
document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const bankCardInput = form.querySelector('#bank_card_number');
            if (bankCardInput) {
                // 移除所有空格，只保留纯数字
                bankCardInput.value = bankCardInput.value.replace(/\s/g, '');
            }
        });
    });
});

// 页面加载时，如果已有银行卡号，进行格式化显示
document.addEventListener('DOMContentLoaded', function() {
    const bankCardInput = document.getElementById('bank_card_number');
    if (bankCardInput && bankCardInput.value) {
        formatBankCard(bankCardInput);
    }
});

// 处理编辑用户表单提交
function handleEditUserSubmit(e) {
    e.preventDefault();
    
    const form = e.target;
    const submitBtn = document.getElementById('editUserSubmit');
    const originalText = submitBtn.innerHTML;
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
    
    const formData = new FormData(form);
    
    fetch('api/edit_user.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(data.message, 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));
            modal.hide();
            
            // 刷新页面
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showToast(data.message, 'danger');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('保存失败，请重试', 'danger');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
}





// 绑定编辑表单提交事件
document.addEventListener('DOMContentLoaded', function() {
    const editForm = document.getElementById('editUserForm');
    if (editForm) {
        editForm.addEventListener('submit', handleEditUserSubmit);
    }
});
// 添加用户表单提交
document.getElementById('addUserForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const form = this;
    const submitBtn = document.getElementById('addUserSubmit');
    const originalText = submitBtn.innerHTML;
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 添加中...';
    
    // 表单验证
    if (!form.checkValidity()) {
        form.classList.add('was-validated');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
        return;
    }
    
    const formData = new FormData(form);
    
    fetch('api/add_user.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 显示成功提示
            showToast(data.message, 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addUserModal'));
            modal.hide();
            
            // 重置表单
            form.reset();
            form.classList.remove('was-validated');
            
            // 刷新页面以显示新用户
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            // 显示错误提示
            showToast(data.message, 'danger');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('添加用户失败，请重试', 'danger');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});



// 全选/取消全选
function toggleSelectAll(checkbox) {
    const checkboxes = document.querySelectorAll('.user-checkbox');
    checkboxes.forEach(cb => {
        cb.checked = checkbox.checked;
    });
    updateBatchActions();
}

// 更新批量操作状态
function updateBatchActions() {
    const selectedCheckboxes = document.querySelectorAll('.user-checkbox:checked');
    const selectedCount = selectedCheckboxes.length;
    const selectedUsersCount = document.getElementById('selectedUsersCount');
    const selectedCountSpan = document.getElementById('selectedCount');
    const batchActions = document.getElementById('batchActions');
    const batchApproveBtn = document.getElementById('batchApproveBtn');
    
    selectedUsersCount.textContent = selectedCount;
    selectedCountSpan.textContent = selectedCount;
    
    if (selectedCount > 0) {
        batchActions.classList.remove('d-none');
        batchApproveBtn.disabled = false;
    } else {
        batchActions.classList.add('d-none');
        batchApproveBtn.disabled = true;
    }
}

// 清除选择
function clearSelection() {
    document.getElementById('selectAll').checked = false;
    const checkboxes = document.querySelectorAll('.user-checkbox');
    checkboxes.forEach(cb => {
        cb.checked = false;
    });
    updateBatchActions();
}

// 获取选中的用户ID
function getSelectedUserIds() {
    const selectedCheckboxes = document.querySelectorAll('.user-checkbox:checked');
    const selectedIds = [];
    selectedCheckboxes.forEach(checkbox => {
        selectedIds.push(parseInt(checkbox.value));
    });
    return selectedIds;
}

// 批量审批选中用户
function batchApprove() {
    const selectedIds = getSelectedUserIds();
    
    if (selectedIds.length === 0) {
        showToast('请先选择要审批的用户', 'warning');
        return;
    }
    
    // 检查是否包含已审批的用户
    let hasApprovedUsers = false;
    selectedIds.forEach(id => {
        const row = document.querySelector(`.user-checkbox[value="${id}"]`).closest('tr');
        const statusBadge = row.querySelector('td:nth-child(7) .badge');
        if (statusBadge && statusBadge.textContent.trim() === '已审批') {
            hasApprovedUsers = true;
        }
    });
    
    let confirmMessage = `确定要审批选中的 ${selectedIds.length} 个用户吗？`;
    if (hasApprovedUsers) {
        confirmMessage += '\n注意：选中的用户中可能包含已审批的用户，重复审批不会产生负面影响。';
    }
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'batch_approve');
    selectedIds.forEach(userId => {
        formData.append('user_ids[]', userId);
    });
    
    const originalText = document.getElementById('batchApproveBtn').innerHTML;
    document.getElementById('batchApproveBtn').disabled = true;
    document.getElementById('batchApproveBtn').innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 审批中...';
    
    fetch('api/approve_users.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(data.message, 'success');
            // 清除选择
            clearSelection();
            // 刷新页面
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showToast(data.message, 'danger');
            document.getElementById('batchApproveBtn').disabled = false;
            document.getElementById('batchApproveBtn').innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('操作失败，请重试', 'danger');
        document.getElementById('batchApproveBtn').disabled = false;
        document.getElementById('batchApproveBtn').innerHTML = originalText;
    });
}

// 一键审批所有未审批用户
function approveAll() {
    // 获取所有未审批的用户
    const unapprovedCheckboxes = document.querySelectorAll('.user-checkbox');
    const unapprovedIds = [];
    
    unapprovedCheckboxes.forEach(checkbox => {
        const row = checkbox.closest('tr');
        const statusBadge = row.querySelector('td:nth-child(7) .badge');
        if (statusBadge && statusBadge.textContent.trim() === '待审批') {
            unapprovedIds.push(parseInt(checkbox.value));
        }
    });
    
    if (unapprovedIds.length === 0) {
        showToast('当前没有待审批的用户', 'info');
        return;
    }
    
    if (!confirm(`确定要审批所有 ${unapprovedIds.length} 个未审批用户吗？`)) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'approve_all');
    
    fetch('api/approve_users.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(data.message, 'success');
            // 刷新页面
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showToast(data.message, 'danger');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('操作失败，请重试', 'danger');
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    updateBatchActions();
});
// 重置表单验证状态
document.getElementById('addUserModal').addEventListener('hidden.bs.modal', function () {
    const form = document.getElementById('addUserForm');
    form.classList.remove('was-validated');
});
// 初始化工具提示
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});
</script>

<?php include __DIR__ . '/footer.php'; ?>